package cn.lovelysia.ymcc.service.impl;

import cn.lovelysia.ymcc.domain.*;
import cn.lovelysia.ymcc.dto.CourseParamDto;
import cn.lovelysia.ymcc.mapper.CourseMapper;
import cn.lovelysia.ymcc.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author elysia
 * @since 2022-12-06
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private ITeacherService teacherService;
    @Autowired
    private ICourseDetailService courseDetailService;
    @Autowired
    private ICourseMarketService courseMarketService;
    @Autowired
    private ICourseResourceService courseResourceService;
    @Autowired
    private ICourseSummaryService courseSummaryService;
    @Autowired
    private ICourseTeacherService courseTeacherService;

    @Override
    public void addCourse(CourseParamDto courseParamDto) {

        //1.保存课程数据t_course
        Course course = courseParamDto.getCourse();
        course.setStatus(Course.OFFLINE);
        course.setLoginId(1L);//暂定
        course.setLoginUserName("测试");
        //chapter_count
        //total_minute
        //teacher_names
        //根据teacharId获取老师的名字，使用，拼接
        List<Teacher> teachers = teacherService.selectBatchIds(courseParamDto.getTeacharIds());
        String names = teachers.stream().map(Teacher::getName).collect(Collectors.joining(","));
        course.setTeacherNames(names);
        insert(course);
        //2.保存课程详情t_course_detail
        CourseDetail courseDetail = courseParamDto.getCourseDetail();
        courseDetail.setId(course.getId());
        courseDetailService.insert(courseDetail);
        //3.保存营销数据t_course_market
        CourseMarket courseMarket = courseParamDto.getCourseMarket();
        courseMarket.setId(course.getId());
        courseMarketService.insert(courseMarket);
        //4.保存资源数据t_course_resource
        CourseResource courseResource = courseParamDto.getCourseResource();
        courseResource.setCourseId(course.getId());
        courseResourceService.insert(courseResource);
        //5.保存销量浏览量汇总数据t_course_summary
        CourseSummary courseSummary = new CourseSummary();
        courseSummary.setId(course.getId());
        courseSummary.setSaleCount(0);
        courseSummary.setViewCount(0);
        courseSummary.setCommentCount(0);
        courseSummaryService.insert(courseSummary);
        //6.保存课程与老师的中间表数据t_course_teacher
        List<Long> teacharIds = courseParamDto.getTeacharIds();
        for (Long teacharId : teacharIds) {
            CourseTeacher courseTeacher = new CourseTeacher();
            courseTeacher.setCourseId(course.getId());
            courseTeacher.setTeacherId(teacharId);
            courseTeacherService.insert(courseTeacher);
        }
    }
}
